<?php
/**
 * 系统消息
 * @return
 * @author yuncran@126.com
 */

namespace app\api\controller;

use app\BaseController;
use app\model\SystemMessageModel;
use app\services\MessageService;

class SystemMessage extends BaseController
{

    /**
     * 获取系统消息
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @author yuncran@126.com
     */
    public function getSystemMessage()
    {
        $user_come_visit_list = SystemMessageModel::field(['id', 'user_id', 'user_id', 'create_time', field('content'), 'describe','is_read'])
            ->where(function ($query) {
                $query->where(['user_id' => $this->uid])->whereOr(['user_id' => 0]);
            })
            ->order(['id' => 'DESC'])
            ->paginate()->each(function ($item) {
                return $item;
            });
        return $this->renderSuccess($user_come_visit_list);
    }


    /**
     * 测试加入系统消息记录
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function systemMessageAdd($messageMutateCode = 100001, $user_id = 3, $user_message_data = [])
    {
        $code = $this->request->param('code', '');
        $message = MessageService::getTemplate($code, $user_message_data = ['username' => 'zhangsan', 'money' => 10, 'gift_name' => '黄金玫瑰']);

//        $message_content = \app\model\SystemMessage::create([
//            'user_id' => $this->uid,
//            'type' => 1,
//            'describe' => $message,
//            'content' => $message
//        ]);

        return $this->renderSuccess($message);
    }


    /**
     * 设置系统消息已读
     * @return void
     * @author yuncran@126.com
     */
    public function saveRead()
    {
        $id = $this->request->param('id');
        if (empty($id)) return $this->renderError(lang('缺少参数'));
        $response = SystemMessageModel::where(['id' => $id])->save(['is_read' => 1, 'update_time' => date('Y-m-d H:i:s', time())]);
        if (!$response) return $this->renderError(lang('error'));
        return $this->renderSuccess([], 'ok');
    }

}